library(ggplot2)

source('utils.R')
load('hh_cces_donors.rdata')

###############################################################################
##FIGURE 1
###############################################################################
cuse <- c("presvote", "housevote", "CC332I", "CC332G", "CC328", "CC321", "CC332E", "CC302b",
          "CC332D", "CC326", "CC329", "CC322_3", "CC332J", "CC320", "CC325", "CC324", "CC422a",
          "CC327", "CC322_6", "CC332A", "CC422b", "CC415r", "CC322_5", "CC322_1", "CC322_2",
          "CC332H", "CC332C", "CC322_4", "CC332F", "CC332B")

gg.all <- gg <- NULL
for(i in cuse){

    ##SUBSET ON MATCHED DONORS
    uu <- rep(TRUE,nrow(cces.donors)) & cces.donors$donated_ns >= 0 
    cf.in <- cces.donors[uu,]
    y <- cces.donors[uu,i] 

    cf.in.all <- cf.in

    ##BINNING 
    qq <- c(seq(-1.8,1.8,.36))
    cfbin.all <- as.numeric((cut(cf.in.all$cfscoreR,round(qq,3),include.lowest=T)))
    tt.all <- table(cfbin.all,y)
    tt.all2 <- tt.all/rowSums(tt.all)

    cname.i <- pi.names[match(i,pi.names[,1]),2]
    gg <- rbind(gg,rbind(data.frame(x=1:nrow(tt.all),y=tt.all2[,2],prt='A',item=cname.i)))

    pcol <- ifelse(cf.in.all$party==100,'blue',
            ifelse(cf.in.all$party==200,'red','orange'))
    gg.all <- rbind(gg.all,data.frame(x=cf.in.all$cfscoreR,
                                      y=y,pcol=pcol,
                                      item=cname.i))
     
}


gg$x2 <- qq[gg[,1]]
q1 <- qplot(data=gg,x=x2,y=y,colour='black',size=.85)
q1 <- q1 + scale_color_identity()
q1 <- q1 + scale_size_identity()
q1 <- q1+facet_wrap(~item,ncol=5)
q1 <- q1 + theme_bw()
q1 <- q1 + theme(strip.switch.pad.wrap=unit(0, "lines"),
                 strip.text=element_text(size=7))
q1 <- q1 + scale_y_continuous(expand=c(0.01,0))
q1 <- q1+ ylab('Proportion in Favor')
q1 <- q1+ xlab('DIME scores')
q1 <- q1 + theme(legend.position='none')

pdf(file='figures/fig_2_cces_dime_binned_scatter.pdf',width=9,height=8)
print(q1)
dev.off()

cairo_ps(file='figures/fig_2_cces_dime_binned_scatter.eps',
         family="mono",
         width=9,height=8)
print(q1)
dev.off()

